package com.hl.toolkit.server.bdpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;


public class O2o_apireverseServlet extends HttpServlet {
 
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 250793993288280073L;
	private ServletConfig scon = null;
	
	public O2o_apireverseServlet() {
		super();
	}
	
	public void destroy() {
		super.destroy(); 
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	/**
	 *接收post请求的方法
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        /**
         * 1、设置编码
         */
		response.setContentType("text/html;charset=gbk");  
		response.setHeader("content-type","text/html;charset=gbk");
		request.setCharacterEncoding("gbk");
		response.setCharacterEncoding("gbk");
		
		PrintWriter out = response.getWriter();
		//打印日志
	    Logger logger =new  BfbSdkComm().printLog("PayQueryOrderByNoServlet");

		logger.log(Level.INFO, "response编码："+response.getCharacterEncoding());
		/**
		 * 2、获取 web.xml的常量值
	     */
	    
	    String sp_no="sp_no=" +scon.getServletContext().getInitParameter("SP_NO");   
	    String input_charset="input_charset=" +scon.getServletContext().getInitParameter("BFB_INTERFACE_INPUT_FORMAT");
	    String version="version=" +scon.getServletContext().getInitParameter("BFB_INTERFACE_VERSION");
	    String sign_method="sign_method=" +scon.getServletContext().getInitParameter("SIGN_METHOD_MD5");
	    
	    //提交地址
	    String BFB_apireverse_ORDER_URL=scon.getServletContext().getInitParameter("BFB_apireverse_ORDER_URL");
	    //订单号
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");  
	    
	    String order_create_time1=formatter.format(System.currentTimeMillis()); 
	    
	    String order_no="order_no=" +"BD"+order_create_time1+(int)(Math.random() * 100); ;
	    
		//给提交参数数值赋值
		String[]array={
				order_no,
				input_charset,
				sign_method,
				sp_no,
				version};
		/**
		 * 4、调用create_bdpay_pay_order_url方法生成百度钱包冲正接口URL
		 *
		 */
		String getURL=new BfbSdkComm().create_bdpay_pay_order_url(array,array,BFB_apireverse_ORDER_URL);
      
		 /**
         * 5、向百付宝发起订单冲正请求
         */
	    HttpClient httpClient =  new  HttpClient();    
	    httpClient.getParams().setParameter(
	    	      HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
	    // 设置 Http 连接超时为5秒    
	    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 5000 );   
	     /* 生成 GetMethod 对象并设置参数 */    
	    GetMethod getMethod =  new  GetMethod(getURL);    
	     // 设置 get 请求超时为 5 秒    
	    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,  5000 );   
	      // 设置请求重试处理，用的是默认的重试处理：请求三次    
	    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new  DefaultHttpMethodRetryHandler());         
	    String responseStr = "" ;    
	     /**
	      * 6、 执行 HTTP GET 请求
	      */ 
	     try  
	     {    
	         int  statusCode = httpClient.executeMethod(getMethod); 
	         /*  判断访问的状态码 */    
	         if  (statusCode != HttpStatus.SC_OK) 
	         {    
	            out.println( "HttpStatus.SC_OK :" + getMethod.getStatusLine());   
	          }    
	      
	        // HTTP响应头部信息，这里简单打印                 	         
	        // 读取 HTTP 响应内容，这里简单打印网页内容    
           
            InputStream ins = getMethod.getResponseBodyAsStream();
            

          BufferedReader br = new BufferedReader(new InputStreamReader(ins,"GBK"));
          StringBuffer sbf = new StringBuffer();
          String line = null;
          while ((line = br.readLine()) != null)
          {
          sbf.append(line);
          }

          br.close();
           
            
          String   result = sbf.toString();
            logger.log(Level.INFO, "getMethod.getResponseBodyAsString()返回的json原文:" +result+"json原文返回值"+"<br/>");
	       
            
            JSONObject resjson = JSONObject.parseObject(result);
            String ret = resjson.getString("ret");
            if(ret.equals("0")){
            JSONObject data=resjson.getJSONObject("content");
            String baifubaoSign = data.getString("sign");
            String verifySign = new BfbSdkComm().verify_apireverse_sign(resjson);
          
       
    		
            	out.println("返回数据           :" + result + "<br/>  ");	
	    	   out.println("本地签名串            :" + verifySign + "本地签名串<br/>  ");
	    	   out.println("百付宝返回签名串:" + baifubaoSign + "百付宝返回签名串<br/> " );
	    	   logger.log(Level.INFO, "本地签名串           : " + verifySign + "本地签名串  \n\r");
	    	   logger.log(Level.INFO, "百付宝返回签名串: " + baifubaoSign + "百付宝返回签名串" );
	    	   if(verifySign.equalsIgnoreCase(baifubaoSign))
	    	   {
	    		   out.println("验证签名通过 <br/>  ");
	    		   logger.log(Level.INFO, "验证签名通过\n\r  ");
	    	   }else 
	    	   {
	    		   out.println("验证签名失败 <br/>  ");
	    		   logger.log(Level.INFO, "请求异常，请检查httpClient\n\r" );
	    	   }
            }else{
            	out.println("返回数据           :" + result + "<br/>  ");	
            }
	 
	      }catch (HttpException e) {    
	         // 发生致命的异常，可能是协议不对或者返回的内容有问题   
	        out.println( "HttpException异常" );   
	        logger.log(Level.INFO, "HttpException异常，请检查代码" );
	      } 
	      finally  
	      {    
	         /* 释放连接 */    
	    	  getMethod.releaseConnection();    
	      }    
		
		//在日志里面打印提交串
		logger.log(Level.INFO, "百度钱包冲正 getURL提交地址：："+getURL);
		
		//打印完成关闭日志
		logger.setLevel(Level.OFF);
	
    }   
	public String getServletInfo() {
		return "O2o_apireverseServlet";
	}
	
	public void init(ServletConfig config) throws ServletException {
		scon = config;
	}

	
}
